<?php

namespace App\Console\Commands;

use App\Jobs\RepayCommonJobQueue;
use App\Jobs\RepayJobQueue;
use App\Jobs\RepayMoneyNotifyJobQueue;
use App\Jobs\RepayMonthJobQueue;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RepayAutoCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'repay:repay_auto {action : money_jinxiao|money_other|setMoney|setOldGuangDa|setDayRepay} {--time=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动还款';

    protected $action;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();

    }

    /**
     * Description: Initialize command action.
     * Author: Gxs
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['money_jinxiao','money_other','setMoney','setOldGuangDa','setDayRepay'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'month', 'common', 'money', 'help'.");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Gxs
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }

    //晋商批扣 8点/22点
    protected function money_jinxiao(){
        //查询所有的可以正常还款的 today >= 还款日期,1 and 3
        //日期,状态,更改状态,全局状态,
        $today = Carbon::today();
        $repaySummaryInfo = RepaySummary::with(['recordOne'=>function($q) use($today) {
            $q->where('status','<>',RepayRecord::STATUS_FOUR);
            $q->where('status','<>',RepayRecord::STATUS_TWO);
            $q->where('pay_off',RepayRecord::PAY_OFF_ONE);
            $q->whereDate('normal_date','<=',$today->toDateString());
        },'recordOne.money'])
            ->where('repay_summaries.status',RepaySummary::STATUS_ONE)
            ->with(['relationUserLoanRequests'=>function($loan) {
                $loan->where('channel',SettingChannel::CHANNEL_JIXIAO);
            }])
            ->chunk(2000, function ($repaySummaryInfo) use($today) {
                foreach ($repaySummaryInfo as $k => $value){
                    //不是晋商跳出
                    if(empty($value->relationUserLoanRequests)){
                        continue;
                    }
                    if(empty($value->recordOne)){
                        continue;
                    }
                    $money = $value->recordOne->money;
                    if($money->status != RepayRecordMoney::STATUS_ONE && $money->status != RepayRecordMoney::STATUS_THREE){
                        continue;
                    }
                    $normal_date = Carbon::parse($value->recordOne->normal_date);
                    if($today->lt($normal_date)){
                        continue;
                    }
                    $flag = RepayRecord::isLastPeriodSuccess($value->recordOne);
                    if(!$flag){
                        continue;
                    }
                    //判断是否达到当日最大次数
                    $is_send_api = RepaySummary::checkApiNumber($value->recordOne->summary_id,$value->recordOne->uid,RepaySummary::MONEY_API);
                    if(!$is_send_api){
                        continue;
                    }
                    DB::beginTransaction();
                    try{
                        //入队列,改变用户状态
                        Log::debug('自动还款:更新用户的状态和资方的还款类型成功---------晋商--------' . $value->recordOne->id);
                        RepaySummary::setCurrentRepayJob($value->recordOne,RepayRecord::REPAY_TYPE_AUTO);
                        DB::commit();
                    }catch (\Exception $e){
                        Log::debug('自动还款:更新用户的状态和资方的还款类型失败' . $e->getMessage() . '----------' . $value->recordOne->id);
                        DB::rollBack();
                    }
                }
            });

    }

    //非晋商批扣  光大/老光大/龙信/众安  8点/18点/22点
    protected function money_other(){
        //查询所有的可以正常还款的 today >= 还款日期,1 and 3
        //日期,状态,更改状态,全局状态,
        $today = Carbon::today();
        $repaySummaryInfo = RepaySummary::with(['recordOne'=>function($q) use($today) {
            $q->where('status','<>',RepayRecord::STATUS_FOUR);
            $q->where('status','<>',RepayRecord::STATUS_TWO);
            $q->where('pay_off',RepayRecord::PAY_OFF_ONE);
            $q->whereDate('normal_date','<=',$today->toDateString());
        },'recordOne.money'])
            ->where('repay_summaries.status',RepaySummary::STATUS_ONE)
            ->with(['relationUserLoanRequests'=>function($loan) {
                $loan->where('channel','<>',SettingChannel::CHANNEL_JIXIAO);
            }])
            ->chunk(2000, function ($repaySummaryInfo) use($today) {
                foreach ($repaySummaryInfo as $k => $value){
                    //去除晋商的数据
                    if(empty($value->relationUserLoanRequests)){
                        continue;
                    }
                    if(empty($value->recordOne)){
                        continue;
                    }
                    $normal_date = Carbon::parse($value->recordOne->normal_date);
                    if($today->lt($normal_date)){
                        continue;
                    }
                    $is_channel = RepaySummary::getLoanChannel($value->id);
                    $money = $value->recordOne->money;
                    if($is_channel){
                        //新光大
                        if($money->status != RepayRecordMoney::STATUS_ONE && $money->status != RepayRecordMoney::STATUS_THREE){
                            continue;
                        }
                    }else{
                        //判断当前是否有协议号
                        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($value->recordOne->bank_cards_id,$value->id);
                        if(!$hold_agreement_num){
                            continue;
                        }
                    }
                    $flag = RepayRecord::isLastPeriodSuccess($value->recordOne);
                    if(!$flag){
                        continue;
                    }
                    //判断是否达到当日最大次数
                    $is_send_api = RepaySummary::checkApiNumber($value->recordOne->summary_id,$value->recordOne->uid,RepaySummary::MONEY_API);
                    if(!$is_send_api){
                        continue;
                    }
                    DB::beginTransaction();
                    try{
                        //入队列,改变用户状态
                        Log::debug('自动还款:更新用户的状态和资方的还款类型成功---------光大/老光大/龙信/众安--------' . $value->recordOne->id);
                        RepaySummary::setCurrentRepayJob($value->recordOne,RepayRecord::REPAY_TYPE_AUTO);
                        DB::commit();
                    }catch (\Exception $e){
                        Log::debug('自动还款:更新用户的状态和资方的还款类型失败' . $e->getMessage() . '----------' . $value->recordOne->id);
                        DB::rollBack();
                    }
                }
            });

    }


//    protected function money(){
//        //查询所有的可以正常还款的 today >= 还款日期,1 and 3
//        //日期,状态,更改状态,全局状态,
//        $repaySummaryInfo = RepaySummary::with(['recordOne'=>function($q){
//            $today = Carbon::today();
//            $q->where('status','<>',RepayRecord::STATUS_FOUR);
//            $q->where('status','<>',RepayRecord::STATUS_TWO);
//            $q->where('pay_off',RepayRecord::PAY_OFF_ONE);
//            $q->whereDate('normal_date','<=',$today->toDateString());
//        },'recordOne.money'])
//            ->where('repay_summaries.status',RepaySummary::STATUS_ONE)
//            ->chunk(2000, function ($repaySummaryInfo) {
//                foreach ($repaySummaryInfo as $k => $value){
//                    if(empty($value->recordOne)){
//                        continue;
//                    }
//                    $today = Carbon::today();
//                    $normal_date = Carbon::parse($value->recordOne->normal_date);
//                    if($today->lt($normal_date)){
//                        continue;
//                    }
//                    $is_channel = RepaySummary::getLoanChannel($value->id);
//                    $money = $value->recordOne->money;
//                    if($is_channel){
//                        //新系统,老系统的晋商,新光大
//                        if($money->status != RepayRecordMoney::STATUS_ONE && $money->status != RepayRecordMoney::STATUS_THREE){
//                            continue;
//                        }
//                    }else{
//                        //判断当前是否有协议号
//                        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($value->recordOne->bank_cards_id,$value->id);
//                        if(!$hold_agreement_num){
//                            continue;
//                        }
//                    }
//                    $flag = RepayRecord::isLastPeriodSuccess($value->recordOne);
//                    if(!$flag){
//                        continue;
//                    }
//                    //判断是否达到当日最大次数
//                    $is_send_api = RepaySummary::checkApiNumber($value->recordOne->summary_id,$value->recordOne->uid,RepaySummary::MONEY_API);
//                    if(!$is_send_api){
//                        continue;
//                    }
//                    DB::beginTransaction();
//                    try{
//                        //入队列,改变用户状态
//                        RepaySummary::setCurrentRepayJob($value->recordOne,RepayRecord::REPAY_TYPE_AUTO);
//                        DB::commit();
//                    }catch (\Exception $e){
//                        Log::debug('自动还款:更新用户的状态和资方的还款类型失败' . $e->getMessage() . '----------' . $value->recordOne->id);
//                        DB::rollBack();
//                    }
//                }
//            });;
//
//    }

    protected function setDayRepay(){
        $day = $this->option('time');
        if(!$day){
            return;
        }
        $day = Carbon::parse($day);
        //查询所有的可以正常还款的 today >= 还款日期,1 and 3
        //日期,状态,更改状态,全局状态,
        $repaySummaryInfo = RepaySummary::with(['recordOne'=>function($q) use($day){
            $q->where('status','<>',RepayRecord::STATUS_FOUR);
            $q->where('status','<>',RepayRecord::STATUS_TWO);
            $q->where('pay_off',RepayRecord::PAY_OFF_ONE);
            $q->whereDate('normal_date','=',$day->toDateString());
        },'recordOne.money'])
            ->where('repay_summaries.status',RepaySummary::STATUS_ONE)
            ->chunk(2000, function ($repaySummaryInfo) use($day) {
                foreach ($repaySummaryInfo as $k => $value){
                    if(empty($value->recordOne)){
                        continue;
                    }
                    $normal_date = Carbon::parse($value->recordOne->normal_date);
                    if($day->lt($normal_date)){
                        continue;
                    }
                    $is_channel = RepaySummary::getLoanChannel($value->id);
                    $money = $value->recordOne->money;
                    if($is_channel){
                        //新系统,老系统的晋商,新光大
                        if($money->status != RepayRecordMoney::STATUS_ONE && $money->status != RepayRecordMoney::STATUS_THREE){
                            continue;
                        }
                    }else{
                        //判断当前是否有协议号
                        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($value->recordOne->bank_cards_id,$value->id);
                        if(!$hold_agreement_num){
                            continue;
                        }
                    }
                    //判断是否达到当日最大次数
                    $is_send_api = RepaySummary::checkApiNumber($value->recordOne->summary_id,$value->recordOne->uid,RepaySummary::MONEY_API);
                    if(!$is_send_api){
                        continue;
                    }
                    $flag = RepayRecord::isLastPeriodSuccess($value->recordOne);
                    if(!$flag){
                        continue;
                    }
                    DB::beginTransaction();
                    try{
                        //入队列,改变用户状态
                        RepaySummary::setCurrentRepayJob($value->recordOne,RepayRecord::REPAY_TYPE_AUTO);
                        DB::commit();
                    }catch (\Exception $e){
                        Log::debug('自动还款:更新用户的状态和资方的还款类型失败' . $e->getMessage() . '----------' . $value->recordOne->id);
                        DB::rollBack();
                    }
                }
            });;

    }


    /**
     * Description:修改 record的status = 2 其他三个表不为2,重新唤起
     * Author:lijiafei
     */
    public function setMoney(){
        $recordInfo = RepayRecord::select(['repay_records.*'])
            ->where('repay_records.status',2)
            ->where('repay_record_moneys.status','<>',2)
            ->where('repay_record_months.status','<>',2)
            ->where('repay_record_commons.status','<>',2)
            ->leftjoin('repay_record_moneys','repay_record_moneys.record_id','repay_records.id')
            ->leftjoin('repay_record_months','repay_record_months.record_id','repay_records.id')
            ->leftjoin('repay_record_commons','repay_record_commons.record_id','repay_records.id')
            ->chunk(2000, function ($recordInfo) {
                if(!empty($recordInfo)){
                    foreach ($recordInfo as $k => $value){
                        if($value->period != 0){
                            RepaySummary::setCurrentRepayJob($value,0,1);
                        }elseif($value->period == 0){
                            RepaySummary::setAllRepayJob($value,0,1);
                        }
                    }
                }
            });


    }

    /**
     *
     */
    public function setOldGuangDa(){
        $info = RepayRecordCommon::where('repay_record_commons.status',RepayRecordCommon::STATUS_FOUR)
            ->where('money_notify_status','<>',RepayRecordCommon::MONEY_NOTIFY_STATUS_FOUR)
            ->where('money_notify_status','<>',RepayRecordCommon::MONEY_NOTIFY_STATUS_TWO)
            ->leftjoin('repay_records','repay_records.id','repay_record_commons.record_id')
            ->leftjoin('repay_summaries','repay_summaries.id','repay_record_commons.summary_id')
            ->where('repay_summaries.loan_channel','LCC201709190009')
            ->where('repay_records.status',RepayRecord::STATUS_FOUR)
            ->whereDate('repay_records.repay_date','>=','2019-02-20')
            ->chunk(1000, function ($info) {
                foreach ($info as $k => $v){
                    if(!empty($v)){
                        RepayMoneyNotifyJobQueue::dispatch($v->record_id);
                    }
                }
            });
    }
}
